package com.oocl.euc.core.maintenance.controller;

import com.oocl.euc.core.maintenance.model.Role;
import com.oocl.euc.core.maintenance.service.RoleService;
import com.oocl.euc.framework.base.controller.RESTController;
import com.oocl.euc.framework.base.service.BaseService;
import com.oocl.euc.framework.common.utils.ResponseEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/rest/role")
public class RoleController extends RESTController<Role, Long> {

    @Autowired RoleService roleService;

    @Override
    protected BaseService<Role, Long> getBaseService() { return roleService; }

    @RequestMapping("/all")
    public ResponseEntity findAll() {
        return ResponseEntityUtil.successInRestful(roleService.findAll());
    }

    @RequestMapping("/find/roleAuthorizations/{roleId}")
    public ResponseEntity findRoleAuthorizationsByRoleId(@PathVariable Long roleId) {
        Role role = roleService.findOne(roleId);
        return ResponseEntityUtil.successInRestful(role);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity add(@RequestBody Role newRole) {
        return ResponseEntityUtil.successInRestful(roleService.save(newRole));
    }

    @RequestMapping(value = "/del/{roleId}", method = RequestMethod.DELETE)
    public ResponseEntity del(@PathVariable Long roleId) {
        roleService.delete(roleId);
        return ResponseEntityUtil.successInRestful(roleId);
    }

    @RequestMapping(value = "/add/authorization", method = RequestMethod.POST)
    public ResponseEntity addAuthorization(@RequestBody Map<String, Object> params){
        Long roleId = Long.valueOf(params.get("roleId").toString());
        String domainIdOrGroupName = (String) params.get("domainIdOrGroupName");
        return ResponseEntityUtil.successInRestful(roleService.addAuthorizationByRoleIdAndDomainIdOrGroupName(roleId, domainIdOrGroupName));
    }

    @RequestMapping(value = "/del/authorization/{roleAuthorizationId}", method = RequestMethod.DELETE)
    public ResponseEntity delRoleAuthorization(@PathVariable Long roleAuthorizationId) {
        roleService.deleteAuthorizationByRoleAuthorizationId(roleAuthorizationId);
        return ResponseEntityUtil.successInRestful(roleAuthorizationId);
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public ResponseEntity updateRole(@RequestBody Role role){
        roleService.update(role);
        return ResponseEntityUtil.successInRestful(role);
    }

}
